<template>
  <div>
    <div class="filter-columns">
      <FilterColumns
        @visibleColumns="visibleColumns"
        :data="titles.map((item) => ({ ...item, checked: true }))"
      />
    </div>
    <el-table
      :data="columns"
      :border="true"
      size="mini"
      style="width: 100%"
      :cell-style="cellStyle"
      :default-sort="{ prop: 'acc', order: 'ascending' }"
    >
      <el-table-column
        v-for="item in visibleTitles"
        :key="item.value"
        :prop="item.value"
        :label="item.label"
        :sortable="true"
        :resizable="true"
        :sort-orders="['ascending', 'descending']"
        :show-overflow-tooltip="false"
        :formatter="formatter"
        :sort-method="sortMethod(item.value)"
      >
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import { reactive, onMounted } from "vue";
import FilterColumns from "./FilterColumns.vue";
import {
  getCellStyle,
  parseNumber,
  sortStdCode,
  parsePnlResponse,
} from "./pnl.util";

const subscribe_url = "http://www.signal9.cn:33077/subscribe_detail";

export default {
  name: "PNL",
  components: {
    FilterColumns,
  },
  setup() {
    const state = reactive({
      titles: [],
      columns: [],
      visibles: undefined,
    });
    onMounted(async () => {
      const source = new EventSource(subscribe_url);
      source.onmessage = (rsp) => {
        const { titles, columns } = parsePnlResponse(rsp);
        state.titles = titles;
        state.columns = columns;
      };
    });
    return state;
  },
  methods: {
    cellStyle({ row, column }) {
      return getCellStyle(row, column);
    },
    formatter(row, column, cellValue) {
      return parseNumber(column, cellValue);
    },
    sortMethod(title) {
      return sortStdCode(title);
    },
    visibleColumns(data = []) {
      this.visibles = data;
    },
  },
  computed: {
    visibleTitles() {
      return this.visibles === undefined
        ? this.titles
        : this.titles.filter(({ value }) => {
            return this.visibles.includes(value);
          });
    },
  },
};
</script>

<style scoped>
.filter-columns {
  position: fixed;
  top: 10px;
  right: 12px;
  z-index: 1;
}
</style>
